package ds.project.test.logic;

import java.io.BufferedReader;
import java.io.File;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.PrintWriter;
import java.net.InetAddress;
import java.net.Socket;

import ds.project.datamodel.CustomException;
import ds.project.protocol.ServerRequests;
import ds.project.utils.FileUtils;

public class DownloadFileThread extends Thread{
	private File downloadDirectory;
	private String downloadFile;
	private InetAddress serverAddress;	
	private int serverTcpPort;	
	private int fileId;
	
	public DownloadFileThread(InetAddress serverAddress, int serverPort, File downloadDirectory, String downloadFile, int fileId)
	{
		this.serverAddress = serverAddress;
		this.serverTcpPort = serverPort;
		this.downloadDirectory = downloadDirectory;
		this.downloadFile = downloadFile;
		this.fileId = fileId;
	}
	
	public void run()
	{
		Socket socketToServer = null;
		PrintWriter out = null;
		BufferedReader in = null;		
		try{			
			socketToServer = new Socket(serverAddress, serverTcpPort);
			out = new PrintWriter(socketToServer.getOutputStream(), true);					
		    in = new BufferedReader(new InputStreamReader(socketToServer.getInputStream()));
		    out.println(ServerRequests.DOWNLOAD_FILE);
		    out.println(downloadFile);
		}		
		catch(IOException e){			
			e.printStackTrace();
			try {
				throw new CustomException(ClientErrorCodes.ERROR_CONNECTING_SERVER_TO_DOWNLOAD, null, "Error conectando con el servidor para la descarga");
			} catch (CustomException e1) {
				// TODO Auto-generated catch block
				e1.printStackTrace();
			}		
		} 
		
		try{  
			//Crea en el archivo en el disco
			String filePath = downloadDirectory.getAbsolutePath() + File.separator + (fileId + downloadFile);
			File f = new File(filePath);
	        if(f.exists()){
	        	f.delete();
	        }
	    
	        FileUtils.SaveStringAsFile(filePath, socketToServer.getInputStream());
	    
	        in.close();
	        out.close();
	        socketToServer.close();
	        if (f.length() <= 0)
	        {
	        	f.delete();
	        	try {
					throw new CustomException(ClientErrorCodes.ERROR_DOWNLOADING_FILE, null, "Error descargando el archivo. El servidor se encuentra ocupado");
				} catch (CustomException e) {
					// TODO Auto-generated catch block
					e.printStackTrace();
				}	
	        }
		}
		catch(IOException e){
			e.printStackTrace();
			try {
				throw new CustomException(ClientErrorCodes.ERROR_DOWNLOADING_FILE, e, "Error descargando el archivo");
			} catch (CustomException e1) {
				// TODO Auto-generated catch block
				e1.printStackTrace();
			}		
		}
	}

}
